package com.argrace.smart.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.R;
import com.argrace.smart.adapter.SubDeviceListAdapter;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.entity.MineZigBeeDeviceListEntity;
import com.argrace.smart.model.LocalDb_DeviceNameAndRoomNameTable;
import com.argrace.smart.model.LocalDb_QingJing_DeviceTable;
import com.argrace.smart.ui.EmptyRecycleView;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.Logg;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by argrace_dev_1 on 2018/2/11.
 */

public class CreateQingJing_ChooseSubDeviceActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    EmptyRecycleView recyclerView;
    SwipeRefreshLayout refreshLayout;
    private SubDeviceListAdapter adapter;
    private ArrayList<MineZigBeeDeviceListEntity> lists = new ArrayList<>();
    private String uuid, name;
    private int pageNo = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subdevicelist);
        init();
    }

    private void init() {
        uuid = getIntent().getStringExtra("uuid");
        name = getIntent().getStringExtra("name");
        setView();
        setTitle(true, false, "添加子设备");
        showRight(true, R.mipmap.head_title_tick);
        //进入搜索产品子设备列表
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit();
            }
        });
        setRefreshing(true);
        onRefresh();
    }

    private void commit() {

        ArrayList<LocalDb_QingJing_DeviceTable> deviceLists = new ArrayList<>();
        deviceLists.addAll(DataSupport.findAll(LocalDb_QingJing_DeviceTable.class));
        for (LocalDb_QingJing_DeviceTable b : deviceLists) {
            Log.i("info", "保存设备之前的设备列表是,uuid=" + b.getUuid() + "LocalDb_DeviceTable_deviceId=" + b.getLocalDb_DeviceTable_deviceId() + "json=" + b.getJson_params());
        }
        for (int i = 0; i < lists.size(); i++) {
            if (lists.get(i).isIs_Selected()) {
                LocalDb_QingJing_DeviceTable entity = new LocalDb_QingJing_DeviceTable();
                entity.setUuid(lists.get(i).getUuid());
                entity.setName(lists.get(i).getName());
                entity.setModel(lists.get(i).getModel());
                entity.setLocalDb_DeviceTable_deviceId(name);
                int result = entity.updateAll("uuid = ? and LocalDb_DeviceTable_deviceId = ?", lists.get(i).getUuid(), name);
                if (result == 0) {
                    entity.save();
                }
                Log.i("info", "保存的结果是" + result);
            }
        }
        deviceLists.clear();
        deviceLists.addAll(DataSupport.findAll(LocalDb_QingJing_DeviceTable.class));
        for (LocalDb_QingJing_DeviceTable b : deviceLists) {
            Log.i("info", "保存设备之后的设备列表是,uuid=" + b.getUuid() + "LocalDb_DeviceTable_deviceId=" + b.getLocalDb_DeviceTable_deviceId() + "json=" + b.getJson_params());
        }
        finish();
    }

    @SuppressLint("ResourceType")
    private void setView() {
        recyclerView = (EmptyRecycleView) findViewById(R.id.recyclerView);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
//        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setItemAnimator(null);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SubDeviceListAdapter(lists, this);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.isFirstOnly(false);
        recyclerView.setAdapter(adapter);
        refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorPrimary), getResources().getColor(R.color.colorPrimary));//getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme)
        refreshLayout.setOnRefreshListener(this);
        adapter.setOnLoadMoreListener(this);
        adapter.setListeners(new SubDeviceListAdapter.OnAdapterItemClickListener() {
            @Override
            public void click(MineZigBeeDeviceListEntity bean, int position) {
                if (bean.isIs_Selected()) {
                    bean.setIs_Selected(false);
                } else {
                    bean.setIs_Selected(true);
                }
                adapter.notifyItemChanged(position);

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onRefresh() {
        setRefreshing(true);
        pageNo = 1;
        getSubDevicelist();
    }

    @Override
    public void onLoadMoreRequested() {
        pageNo++;
        getSubDevicelist();
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

    //查询子设备列表
    private void getSubDevicelist() {
        Log.i("info", "CreateQingJing_ChooseSubDeviceActivity.getSubDevicelist(),start,uuid = " + uuid);
        String method = "mtop.openalink.home.device.infolist";
        HashMap<String, Object> params = new HashMap<>();
        params.put("uuid", uuid);
        params.put("pageNo", pageNo);
        params.put("pageSize", "10");
        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                JSONObject dataObj = JSON.parseObject(transitoryResponse.data.toString());
                Logg.i("info", "子设备列表获取成功data=" + dataObj.toJSONString());
                List<MineZigBeeDeviceListEntity> beans = JSON.parseArray(dataObj.getString("deviceList"), MineZigBeeDeviceListEntity.class);

                if (beans == null || beans.size() == 0) {

                    adapter.loadMoreEnd();
//                    adapter.notifyDataSetChanged();
                } else {

                    for (int i = 0; i < beans.size(); i++) {
                        List<LocalDb_DeviceNameAndRoomNameTable> beans_local = DataSupport.where("uuid = ?", beans.get(i).getUuid()).find(LocalDb_DeviceNameAndRoomNameTable.class);
                        if (beans_local != null && beans_local.size() > 0) {
                            beans.get(i).setName(beans_local.get(0).getNickName());
                        }
                    }
                    if (pageNo == 1) {
                        lists.clear();
                        lists.addAll(beans);
                        adapter.setNewData(lists);
                        setRefreshing(false);
                        adapter.loadMoreComplete();
                    } else {
                        adapter.addData(beans);
                        setRefreshing(false);
                        adapter.loadMoreComplete();
                    }

                }


            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                setRefreshing(false);
                if (pageNo > 1) {
                    pageNo--;
                }
                adapter.loadMoreFail();
                Log.i("info", "获取子设备列表失败,msg = " + aError.getMsg() + aError.getCode());
            }
        });

    }
}
